package com.skyline.courier.mq.provider.gearman;

/**
 * Gearman地址类
 * 
 * @author wuqh
 * 
 */
public class GearmanAddress {
	private static final int DEFAULT_PORT = 4730;
	private final String host;
	private final int port;

	public GearmanAddress(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public String getHost() {
		return host;
	}

	public int getPort() {
		return port;
	}

	public static GearmanAddress parseAddress(String addressString) {
		int idx = addressString.indexOf(':');
		return (idx == -1) ? new GearmanAddress(addressString, DEFAULT_PORT) : new GearmanAddress(
				addressString.substring(0, idx), Integer.parseInt(addressString.substring(idx + 1)));
	}

	public static GearmanAddress[] parseAddresses(String addresses) {
		String[] addrs = addresses.split(" *, *");
		GearmanAddress[] res = new GearmanAddress[addrs.length];
		for (int i = 0; i < addrs.length; i++) {
			res[i] = GearmanAddress.parseAddress(addrs[i]);
		}
		return res;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null || getClass() != obj.getClass())
			return false;
		final GearmanAddress addr = (GearmanAddress) obj;
		return host.equals(addr.host) && port == addr.port;
	}

	@Override
	public String toString() {
		return host + ":" + port;
	}
}
